/**
 * 融资服务页面组件 - 智能融资评估与申请管理界面
 *
 * 开发人员：唐梓鑫
 * 开发时间：2025-10-30 至 2025-11-05
 * 模块职责：提供融资申请、财务健康评估、融资渠道推荐等完整融资服务功能界面
 *
 * 技术要点：
 * - 融资申请表单和业务逻辑处理
 * - AI财务健康评估结果可视化展示
 * - 融资渠道对比和成本计算功能
 * - 美团品牌风格的卡片式布局设计
 * - 前后端数据交互和状态同步机制
 *
 * 开发故事：负责融资服务的完整前端界面实现，与后端融资AI分析服务深度集成，为企业提供专业的融资决策支持界面。
 */
<template>
  <div class="page-container">
    <div class="page-header">
      <h1 class="page-title">融资服务</h1>
      <p class="page-subtitle">智能融资评估与申请管理</p>
    </div>
    
    <!-- 财务健康状况概览 -->
    <div class="card-section">
      <div class="card-section-title">
        <i class="el-icon-pie-chart"></i>
        财务健康状况
        <el-button size="mini" type="primary" @click="loadFinancialHealth" style="float: right;">刷新</el-button>
      </div>
      <div v-if="financialHealth" class="health-overview">
        <div class="health-score">
          <div class="score-circle" :class="getHealthClass(financialHealth.overallHealth)">
            <span class="score-text">{{getHealthText(financialHealth.overallHealth)}}</span>
          </div>
        </div>
        <div class="health-details">
          <p class="health-timing">{{financialHealth.timing}}</p>
          <div v-if="financialHealth.riskFactors && financialHealth.riskFactors.length" class="risk-factors">
            <h4>风险因素：</h4>
            <ul>
              <li v-for="risk in financialHealth.riskFactors" :key="risk">{{risk}}</li>
            </ul>
          </div>
          <div v-if="financialHealth.improvementSuggestions && financialHealth.improvementSuggestions.length" class="suggestions">
            <h4>改进建议：</h4>
            <ul>
              <li v-for="suggestion in financialHealth.improvementSuggestions" :key="suggestion">{{suggestion}}</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 融资渠道推荐 -->
    <div class="card-section">
      <div class="card-section-title">
        <i class="el-icon-bank-card"></i>
        融资渠道推荐
        <el-button size="mini" type="primary" @click="loadChannels" style="float: right;">刷新</el-button>
      </div>
      <div v-if="channels.length" class="channels-grid">
        <div v-for="channel in channels" :key="channel.id" class="channel-card" @click="selectChannel(channel)">
          <div class="channel-header">
            <h4>{{channel.channel_name}}</h4>
            <span class="channel-type">{{getChannelTypeText(channel.channel_type)}}</span>
          </div>
          <div class="channel-details">
            <div class="rate-info">
              <span class="rate-label">利率：</span>
              <span class="rate-value">{{(channel.interest_rate * 100).toFixed(2)}}%</span>
            </div>
            <div class="amount-info">
              <span class="amount-label">额度：</span>
              <span class="amount-value">¥{{formatMoney(channel.min_amount)}} - ¥{{formatMoney(channel.max_amount)}}</span>
            </div>
            <div class="term-info">
              <span class="term-label">期限：</span>
              <span class="term-value">{{channel.term_months}}个月</span>
            </div>
          </div>
          <div class="channel-advantages">
            <p><strong>优势：</strong>{{channel.advantages}}</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新建融资申请 -->
    <div class="card-section">
      <div class="card-section-title">
        <i class="el-icon-edit"></i>
        新建融资申请
      </div>
      <el-form :model="form" label-width="120px" style="max-width: 600px;">
        <el-form-item label="申请金额">
          <el-input-number v-model="form.requestedAmount" :min="1000" :step="1000" :controls="false" style="width:100%"></el-input-number>
        </el-form-item>
        <el-form-item label="用途说明">
          <el-input v-model="form.purpose" type="textarea" :rows="3" placeholder="请简要说明融资用途"></el-input>
        </el-form-item>
        <el-form-item label="推荐渠道">
          <el-select v-model="form.recommendedChannel" placeholder="选择融资渠道" style="width:100%">
            <el-option v-for="channel in channels" :key="channel.id" 
                       :label="channel.channel_name" 
                       :value="channel.channel_type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submit">提交申请</el-button>
          <el-button @click="reset">重置</el-button>
          <el-button type="success" @click="calculateCost" :disabled="!form.recommendedChannel">计算成本</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 成本计算弹窗 -->
    <el-dialog title="融资成本计算" :visible.sync="costDialogVisible" width="600px">
      <div v-if="costCalculation" class="cost-calculation">
        <div class="cost-summary">
          <h3>{{costCalculation.channelName}}</h3>
          <div class="cost-details">
            <div class="cost-item">
              <span class="cost-label">申请金额：</span>
              <span class="cost-value">¥{{formatMoney(costCalculation.requestedAmount)}}</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">年利率：</span>
              <span class="cost-value">{{costCalculation.interestRate}}%</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">期限：</span>
              <span class="cost-value">{{costCalculation.termMonths}}个月</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">总利息：</span>
              <span class="cost-value">¥{{formatMoney(costCalculation.totalInterest)}}</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">总成本：</span>
              <span class="cost-value">¥{{formatMoney(costCalculation.totalCost)}}</span>
            </div>
            <div class="cost-item">
              <span class="cost-label">月还款：</span>
              <span class="cost-value">¥{{formatMoney(costCalculation.monthlyPayment)}}</span>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 融资申请列表 -->
    <div class="card-section">
      <div class="card-section-title">
        <i class="el-icon-document-checked"></i>
        我的融资申请
      </div>
      <el-table :data="list" style="width:100%">
        <el-table-column prop="id" label="#" width="80"/>
        <el-table-column prop="requestedAmount" label="申请金额" width="150">
          <template slot-scope="{row}">
            <span style="color: var(--primary-color); font-weight: 600;">¥{{formatMoney(row.requestedAmount)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="purpose" label="用途" show-overflow-tooltip/>
        <el-table-column prop="score" label="评分" width="120">
          <template slot-scope="{row}">
            <el-tag v-if="row.score" :type="row.score >= 80 ? 'success' : row.score >= 60 ? 'warning' : 'danger'">
              {{row.score}}分
            </el-tag>
            <span v-else style="color: var(--text-tertiary);">待评估</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="120">
          <template slot-scope="{row}">
            <span :class="['status-tag', statusClass(row.status)]">{{statusText(row.status)}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="申请时间" width="180"/>
        <el-table-column label="操作" width="200">
          <template slot-scope="{row}">
            <el-button size="mini" @click="viewDetail(row)">查看详情</el-button>
            <el-button size="mini" type="info" @click="evaluateRequest(row)">智能评估</el-button>
            <el-button size="mini" type="warning" v-if="row.status==='DRAFT'" @click="updateScore(row)">评分</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div v-if="!list.length" class="empty-state">
        <i class="el-icon-document"></i>
        <p>暂无融资申请记录</p>
      </div>
    </div>

    <!-- 智能评估弹窗 -->
    <el-dialog title="智能融资评估" :visible.sync="evaluationDialogVisible" width="800px">
      <div v-if="evaluationResult" class="evaluation-result">
        <div class="evaluation-header">
          <h3>申请评估结果</h3>
          <div class="overall-score">
            <span class="score-label">综合评分：</span>
            <span class="score-value" :class="getScoreClass(evaluationResult.overallScore)">{{evaluationResult.overallScore}}分</span>
          </div>
        </div>
        <div class="evaluation-details">
          <div class="recommendation">
            <h4>评估建议：</h4>
            <p>{{evaluationResult.recommendation}}</p>
          </div>
          <div v-if="evaluationResult.metrics && evaluationResult.metrics.length" class="metrics-details">
            <h4>财务指标分析：</h4>
            <el-table :data="evaluationResult.metrics" size="mini">
              <el-table-column prop="metric_name" label="指标名称" width="120"/>
              <el-table-column prop="metric_value" label="实际值" width="100"/>
              <el-table-column prop="benchmark_value" label="基准值" width="100"/>
              <el-table-column prop="industry_average" label="行业平均" width="100"/>
              <el-table-column prop="risk_level" label="风险等级" width="100">
                <template slot-scope="{row}">
                  <el-tag :type="getRiskTagType(row.risk_level)" size="mini">{{getRiskText(row.risk_level)}}</el-tag>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import http from '../api/http'

export default {
  data(){
    return {
      enterpriseId: parseInt(localStorage.getItem('enterpriseId')) || 1,
      userId: 1,
      list: [],
      channels: [],
      financialHealth: null,
      costCalculation: null,
      evaluationResult: null,
      costDialogVisible: false,
      evaluationDialogVisible: false,
      form: {
        requestedAmount: 100000,
        purpose: '',
        recommendedChannel: ''
      }
    }
  },
  created(){
    this.load()
    this.loadChannels()
    this.loadFinancialHealth()
  },
  methods: {
    async load(){
      try {
        const { data } = await http.get(`/enterprises/${this.enterpriseId}/financing`)
        if(data.code === 0) this.list = data.data
      } catch(e) {
        console.error(e)
      }
    },
    async loadChannels(){
      try {
        const { data } = await http.get(`/enterprises/${this.enterpriseId}/financing/channels`)
        if(data.code === 0) this.channels = data.data
      } catch(e) {
        console.error(e)
      }
    },
    async loadFinancialHealth(){
      try {
        const { data } = await http.get(`/enterprises/${this.enterpriseId}/financing/health`)
        if(data.code === 0) {
          this.financialHealth = data.data
          // 获取融资时机建议
          const recommendations = await this.getRecommendations()
          if(recommendations) {
            this.financialHealth.timing = recommendations.timing
          }
        }
      } catch(e) {
        console.error(e)
      }
    },
    async getRecommendations(){
      try {
        const { data } = await http.get(`/enterprises/${this.enterpriseId}/financing/recommendations`)
        if(data.code === 0) return data.data
      } catch(e) {
        console.error(e)
      }
      return null
    },
    async submit(){
      if(!this.form.requestedAmount){
        return this.$message.warning('请输入申请金额')
      }
      try {
        const { data } = await http.post(`/enterprises/${this.enterpriseId}/financing`, null, {
          params: {
            userId: this.userId,
            requestedAmount: this.form.requestedAmount,
            purpose: this.form.purpose
          }
        })
        if(data.code === 0){
          this.$message.success('申请提交成功')
          this.reset()
          this.load()
        }
      } catch(e) {
        this.$message.error(e.response?.data?.message || '提交失败')
      }
    },
    async calculateCost(){
      if(!this.form.recommendedChannel || !this.form.requestedAmount) {
        return this.$message.warning('请先选择融资渠道和输入申请金额')
      }
      
      // 先创建一个临时申请来计算成本
      try {
        const { data } = await http.post(`/enterprises/${this.enterpriseId}/financing`, null, {
          params: {
            userId: this.userId,
            requestedAmount: this.form.requestedAmount,
            purpose: this.form.purpose || '成本计算'
          }
        })
        
        if(data.code === 0) {
          const requestId = data.data.id
          const costData = await http.get(`/enterprises/${this.enterpriseId}/financing/${requestId}/cost`, {
            params: { channelType: this.form.recommendedChannel }
          })
          
          if(costData.data.code === 0) {
            this.costCalculation = costData.data.data
            this.costDialogVisible = true
          }
        }
      } catch(e) {
        this.$message.error('成本计算失败')
      }
    },
    async evaluateRequest(row){
      try {
        const { data } = await http.get(`/enterprises/${this.enterpriseId}/financing/${row.id}/evaluate`)
        if(data.code === 0) {
          this.evaluationResult = data.data
          this.evaluationDialogVisible = true
        }
      } catch(e) {
        this.$message.error('评估失败')
      }
    },
    selectChannel(channel){
      this.form.recommendedChannel = channel.channel_type
    },
    reset(){
      this.form = { requestedAmount: 100000, purpose: '', recommendedChannel: '' }
    },
    formatMoney(val){
      if(!val) return '0.00'
      return parseFloat(val).toLocaleString('zh-CN', {minimumFractionDigits: 2, maximumFractionDigits: 2})
    },
    statusText(status){
      const map = {
        'DRAFT': '草稿',
        'SUBMITTED': '已提交',
        'EVALUATED': '已评估',
        'REJECTED': '已拒绝',
        'APPROVED': '已通过'
      }
      return map[status] || status
    },
    statusClass(status){
      const map = {
        'DRAFT': 'created',
        'SUBMITTED': 'pending',
        'EVALUATED': 'pending',
        'REJECTED': 'failed',
        'APPROVED': 'success'
      }
      return map[status] || ''
    },
    getChannelTypeText(type){
      const map = {
        'BANK_LOAN': '银行贷款',
        'EQUITY_FINANCING': '股权融资',
        'SUPPLY_CHAIN': '供应链金融',
        'CROWDFUNDING': '众筹',
        'GOVERNMENT_SUBSIDY': '政府补贴'
      }
      return map[type] || type
    },
    getHealthClass(health){
      const map = {
        'EXCELLENT': 'excellent',
        'GOOD': 'good',
        'FAIR': 'fair',
        'POOR': 'poor'
      }
      return map[health] || 'fair'
    },
    getHealthText(health){
      const map = {
        'EXCELLENT': '优秀',
        'GOOD': '良好',
        'FAIR': '一般',
        'POOR': '较差'
      }
      return map[health] || '一般'
    },
    getScoreClass(score){
      if(score >= 80) return 'score-excellent'
      if(score >= 60) return 'score-good'
      if(score >= 40) return 'score-fair'
      return 'score-poor'
    },
    getRiskTagType(risk){
      const map = {
        'LOW': 'success',
        'MEDIUM': 'warning',
        'HIGH': 'danger',
        'CRITICAL': 'danger'
      }
      return map[risk] || 'info'
    },
    getRiskText(risk){
      const map = {
        'LOW': '低风险',
        'MEDIUM': '中风险',
        'HIGH': '高风险',
        'CRITICAL': '极高风险'
      }
      return map[risk] || risk
    },
    viewDetail(row){
      this.$alert(`申请金额: ¥${this.formatMoney(row.requestedAmount)}<br>用途: ${row.purpose || '未填写'}<br>评分: ${row.score || '待评估'}`, '融资申请详情', {
        dangerouslyUseHTMLString: true
      })
    },
    async updateScore(row){
      this.$prompt('请输入评分（0-100）', '融资评分', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效的数字'
      }).then(async ({ value }) => {
        const score = parseInt(value)
        if(score < 0 || score > 100){
          return this.$message.error('评分范围应在0-100之间')
        }
        try {
          const { data } = await http.post(`/enterprises/${this.enterpriseId}/financing/${row.id}/score`, null, {
            params: { score }
          })
          if(data.code === 0){
            this.$message.success('评分成功')
            this.load()
          }
        } catch(e) {
          this.$message.error(e.response?.data?.message || '评分失败')
        }
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: 28px;
  font-weight: 600;
  color: var(--primary-color);
  margin: 0 0 8px 0;
}

.page-subtitle {
  font-size: 16px;
  color: var(--text-color-regular);
  margin: 0;
}

.card-section {
  background: white;
  border-radius: 8px;
  box-shadow: var(--box-shadow-light);
  margin-bottom: 24px;
  padding: 24px;
}

.card-section-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-color-primary);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.card-section-title i {
  margin-right: 8px;
  color: var(--primary-color);
}

/* 财务健康状况样式 */
.health-overview {
  display: flex;
  gap: 30px;
  align-items: center;
}

.health-score {
  flex-shrink: 0;
}

.score-circle {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  font-weight: 600;
  color: white;
}

.score-circle.excellent {
  background: linear-gradient(135deg, #06C05F, #04A84A);
}

.score-circle.good {
  background: linear-gradient(135deg, #FFD100, #E6B800);
}

.score-circle.fair {
  background: linear-gradient(135deg, #FF9500, #E6850E);
}

.score-circle.poor {
  background: linear-gradient(135deg, #FF3B30, #E6342A);
}

.health-details {
  flex: 1;
}

.health-timing {
  font-size: 16px;
  color: var(--text-color-primary);
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 4px solid var(--primary-color);
}

.risk-factors, .suggestions {
  margin-top: 16px;
}

.risk-factors h4, .suggestions h4 {
  font-size: 14px;
  color: var(--text-color-primary);
  margin: 0 0 8px 0;
}

.risk-factors ul, .suggestions ul {
  margin: 0;
  padding-left: 20px;
}

.risk-factors li {
  color: #FF3B30;
  font-size: 14px;
  margin-bottom: 4px;
}

.suggestions li {
  color: #06C05F;
  font-size: 14px;
  margin-bottom: 4px;
}

/* 融资渠道样式 */
.channels-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.channel-card {
  border: 2px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.channel-card:hover {
  border-color: var(--primary-color);
  box-shadow: 0 4px 12px rgba(255, 209, 0, 0.2);
  transform: translateY(-2px);
}

.channel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.channel-header h4 {
  margin: 0;
  font-size: 16px;
  color: var(--text-color-primary);
}

.channel-type {
  background: var(--primary-color);
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.channel-details {
  margin-bottom: 16px;
}

.rate-info, .amount-info, .term-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.rate-label, .amount-label, .term-label {
  color: var(--text-color-regular);
  font-size: 14px;
}

.rate-value {
  color: #FF3B30;
  font-weight: 600;
}

.amount-value, .term-value {
  color: var(--text-color-primary);
  font-weight: 600;
}

.channel-advantages p {
  margin: 0;
  font-size: 14px;
  color: var(--text-color-regular);
  line-height: 1.5;
}

/* 成本计算弹窗样式 */
.cost-calculation {
  padding: 20px;
}

.cost-summary h3 {
  margin: 0 0 20px 0;
  color: var(--primary-color);
  font-size: 20px;
}

.cost-details {
  display: grid;
  gap: 12px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.cost-label {
  color: var(--text-color-regular);
  font-size: 14px;
}

.cost-value {
  color: var(--text-color-primary);
  font-weight: 600;
  font-size: 16px;
}

/* 智能评估弹窗样式 */
.evaluation-result {
  padding: 20px;
}

.evaluation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #e4e7ed;
}

.evaluation-header h3 {
  margin: 0;
  color: var(--text-color-primary);
  font-size: 20px;
}

.overall-score {
  display: flex;
  align-items: center;
  gap: 12px;
}

.score-label {
  color: var(--text-color-regular);
  font-size: 16px;
}

.score-value {
  font-size: 24px;
  font-weight: 600;
  padding: 8px 16px;
  border-radius: 6px;
}

.score-excellent {
  background: #06C05F;
  color: white;
}

.score-good {
  background: #FFD100;
  color: white;
}

.score-fair {
  background: #FF9500;
  color: white;
}

.score-poor {
  background: #FF3B30;
  color: white;
}

.evaluation-details {
  margin-top: 20px;
}

.recommendation {
  margin-bottom: 24px;
}

.recommendation h4 {
  margin: 0 0 12px 0;
  color: var(--text-color-primary);
  font-size: 16px;
}

.recommendation p {
  margin: 0;
  padding: 16px;
  background: #f0f9ff;
  border-radius: 6px;
  border-left: 4px solid var(--primary-color);
  color: var(--text-color-primary);
  line-height: 1.6;
}

.metrics-details h4 {
  margin: 0 0 16px 0;
  color: var(--text-color-primary);
  font-size: 16px;
}

/* 状态标签样式 */
.status-tag {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-tag.created {
  background: #e1f5fe;
  color: #0277bd;
}

.status-tag.pending {
  background: #fff3e0;
  color: #f57c00;
}

.status-tag.success {
  background: #e8f5e8;
  color: #2e7d32;
}

.status-tag.failed {
  background: #ffebee;
  color: #c62828;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px;
  color: var(--text-color-regular);
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #c0c4cc;
}

.empty-state p {
  margin: 0;
  font-size: 16px;
}
</style>

